/*
 *	Copyright (c) liberty 2016
 *	cn.com.libertymutual.insure.service.impl
 *  Create Date 2016年4月7日
 *	@author tracy.liao
 */
package cn.com.libertymutual.sp.service.impl;

import static cn.com.libertymutual.core.util.Constants.SEQ_ORDER_NO;
import static cn.com.libertymutual.core.util.Constants.SEQ_USER_CODE;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.core.util.DateUtil;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.sp.dao.SpOrderDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sys.service.api.ISequenceService;

/**
 * 系统序列service层实现类
 * @author tracy.liao
 * @date 2016年4月7日
 */
@Service("sequenceService")
public class SequenceServiceImpl implements ISequenceService {

	private Logger log = LoggerFactory.getLogger(getClass());
	
	private final String SEQ_ORDER_FLAG_PRF = "SEQ_ORDER_FLAG:";
	
	@Resource private RedisUtils redisUtil;
	@Resource private UserDao userDao;
	@Resource(name="spOrderDao") private SpOrderDao orderDao;
	
	private static String CURR_DATE = DateUtil.getNowDate("yyMMdd");
	
	@PostConstruct
	private void initSequence() {
		log.info("初始化序列号");

		String  result = userDao.findMaxIdAndCodeOfAll();

		String id;
		if( result == null || result.length() < 5 ) {
			id = "1";
		}
		else {
			id = result.substring(2);
		}
		redisUtil.set(SEQ_USER_CODE, Long.parseLong(id));
		
		log.info("用户ID初始化完毕-{}", id);
		
		//171115310500000001
		result = orderDao.findMaxIdAndNoOfToday();

		if( result == null || result.length() < 12 ) {
			id = "1";
		}
		else {
			id = result.substring(10);
		}
		redisUtil.set(SEQ_ORDER_NO, Long.parseLong(id));
		
		log.info("订单号初始化完毕-{}", id);
		
	}
	
	/**
	 * 获得用户CODE的序列号 WX00000091
	 * source : 终端来源
	 */
	@Override
	public String getUserCodeSequence(String source) {
		
		synchronized (source) {
			long v = redisUtil.incr(SEQ_USER_CODE);
			if( v < 2 ) {
				initSequence();
				v = redisUtil.incr(SEQ_USER_CODE);
			}
			return String.format("%s%08d", source, v);
		}
		
	}

	/**
	 * 获得订单号序列
	 * riskCode - 险种代码
	 */
	@Override
	public String getOrderSequence(String riskCode) {
		//171115310500000001
		synchronized (riskCode) {
			
			String _date = DateUtil.getNowDate("yyMMdd");
			if( CURR_DATE.compareTo( _date ) > 0 && !redisUtil.hashKey(SEQ_ORDER_FLAG_PRF+_date) ) {
				redisUtil.set(SEQ_ORDER_FLAG_PRF+_date, _date);
				redisUtil.set(SEQ_ORDER_NO, 1);
				redisUtil.deleteWithPrefix(SEQ_ORDER_FLAG_PRF+CURR_DATE);
				CURR_DATE = _date;
			}
			
			long v = redisUtil.incr(SEQ_ORDER_NO);
			if( v < 1 ) {
				initSequence();
				v = redisUtil.incr(SEQ_ORDER_NO);
			}

			return String.format("%s%s%08d", DateUtil.getNowDate("yyMMdd"), riskCode, v);
		}
	}

}
